package me.skyun.androidarch.common;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Environment;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.StatFs;
import android.service.wallpaper.WallpaperService;
import android.text.format.Formatter;
import android.util.Log;


import junit.framework.Assert;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by skyun on 17/8/20.
 */

public class Utils {
    public static List<ApplicationInfo> getApps(Context context) {
        PackageManager pm = context.getPackageManager();
        List<ApplicationInfo> appInfos = pm.getInstalledApplications(PackageManager.MATCH_UNINSTALLED_PACKAGES);
        return appInfos;
    }

    public static List<String> getAppNames(Context context) {
        List<ApplicationInfo> appInfos = getApps(context);
        List<String> appNames = new ArrayList<>(appInfos.size());
        PackageManager pm = context.getPackageManager();
        for (ApplicationInfo app : appInfos) {
            appNames.add(app.loadLabel(pm).toString());
        }
        return appNames;
    }


    // Drawable转换成Bitmap
    public static Bitmap drawable2Bitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }
        Bitmap bitmap = Bitmap.createBitmap(
                drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight(),
                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }

    // Drawable转换成byte[]
    public static byte[] drawable2Bytes(Drawable d) {
        Bitmap bitmap = drawable2Bitmap(d);
        return bitmap2Bytes(bitmap);
    }

    // Bitmap转换成byte[]
    public static byte[] bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    // byte[]转换成Bitmap
    public static Bitmap bytes2Bitmap(byte[] b) {
        if (b.length != 0) {
            return BitmapFactory.decodeByteArray(b, 0, b.length);
        }
        return null;
    }

    // 将InputStream转换成Bitmap
    public static Bitmap inputStream2Bitmap(InputStream is) {
        return BitmapFactory.decodeStream(is);
    }

    public static byte[] parcelable2Bytes(Parcelable parcelable) {
        Parcel parcel = Parcel.obtain();
        parcel.writeParcelable(parcelable, 0);
        byte[] bytes = parcel.marshall();
        parcel.recycle();
        return bytes;
    }

    public static <T> T bytes2Parcelable(byte[] bytes, Parcelable.Creator<T> creator) {
        Parcel parcel = Parcel.obtain();
        parcel.writeByteArray(bytes);
        T obj = creator.createFromParcel(parcel);
        parcel.recycle();
        return obj;
    }

    public static byte[] inputStream2Bytes(InputStream is, int count) {
        byte[] bytes = new byte[count];
        int read = 0;
        try {
            while (read < count) {
                read += is.read(bytes, read, count - read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytes;
    }

    public static Parcel inputStream2Parcel(InputStream is, int count) {
        return bytes2Parcel(inputStream2Bytes(is, count));
    }

    public static Parcel bytes2Parcel(byte[] bytes) {
        Parcel parcel = Parcel.obtain();
        parcel.writeByteArray(bytes);
        return parcel;
    }

    public static PackageInfo getAppPackageInfo(Context context, String packName) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(packName, 0);
            return info;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getAppVersion(Context context, String packName) {
        return getAppPackageInfo(context, packName).versionName;
    }

    public static String appInfo2String(Context context, ApplicationInfo app) {
        String name = app.loadLabel(context.getPackageManager()).toString();
        return name + "|" + app.packageName + "|" + getAppVersion(context, app.packageName);
    }

    /**
     * 获取所有已安装的皮肤主题
     *
     * @return
     */
    public static ArrayList<PackageInfo> getAllTheme(Context context) {
        ArrayList<PackageInfo> skinList = new ArrayList<>();
        List<PackageInfo> packs = context.getPackageManager().getInstalledPackages(0);
        for (PackageInfo p : packs) {
            if (isSkinPackage(p.packageName)) {
                skinList.add(p);
            }
        }
        return skinList;
    }

    /**
     * 判断是否是皮肤主题
     */
    public static boolean isSkinPackage(String packageName) {
        return true;
//        String rex = Contact.SKIN_APP_PACKNAME + "\\w";
//        Pattern pattern = Pattern.compile(rex);
//        Matcher matcher = pattern.matcher(packageName);
//        return matcher.find();
    }

    public static JSONObject getDeviceInfo(Context context) {
        JSONObject info = new JSONObject();
        try {
            info.put("品牌", Build.BRAND);
            info.put("型号", Build.MODEL);
            info.put("系统版本", Build.VERSION.RELEASE);
            info.put("内存容量", getRomTotalSize(context));
            info.put("SD卡容量", getSDTotalSize(context));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return info;
    }

    /**
     * 获取手机品牌
     *
     * @return
     */
    public static String getPhoneBrand() {
        return android.os.Build.BRAND;
    }

    public static String getRomTotalSize(Context context) {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        return Formatter.formatFileSize(context, blockSize * totalBlocks);
    }

    public static String getSDTotalSize(Context context) {
        File path = Environment.getExternalStorageDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        return Formatter.formatFileSize(context, blockSize * totalBlocks);
    }

    public static void logMsg(String msg) {
        Log.d("", msg);
    }

    public static List<ResolveInfo> getWatchFaces(Context context) {
        Intent intent = new Intent(WallpaperService.SERVICE_INTERFACE);
        intent.addCategory("com.google.android.wearable.watchface.category.WATCH_FACE");
        List<ResolveInfo> resolveInfos = context.getPackageManager().queryIntentServices(intent,
                PackageManager.GET_RESOLVED_FILTER | PackageManager.GET_META_DATA);
        return resolveInfos;
    }

    public static List<String> getWatchFaceNames(Context context) {
        List<ResolveInfo> resolveInfos = getWatchFaces(context);
        List<String> names = new ArrayList<>(resolveInfos.size());
        for (int i = 0; i < resolveInfos.size(); i++) {
            String name = resolveInfos.get(i).serviceInfo.name;
            if (name != null) {
                names.add(name);
            }
        }
        return names;
    }
}


